

package com.yq.lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Simple to Introduction
 * className: MyCounter
 *
 * @author EricYang
 * @version 2018/5/8 19:32
 */
public class MyCounter {
    public final static Map<String, AtomicLong> aMap = new HashMap();

    public final static Map<String, String> bMap = new HashMap();

    public static synchronized void increaseA(String key, int increase) {
        System.out.println("AThreadId:"+ Thread.currentThread().getId() + " :" + System.currentTimeMillis());
        AtomicLong counter = aMap.get(key);
        if (counter == null) {
            counter = new AtomicLong(0);
            aMap.put(key, counter);
        }

        counter.addAndGet(increase);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static synchronized void increaseB(String key, String value) {
        System.out.println("BThreadId:"+ Thread.currentThread().getId() + " :" + System.currentTimeMillis());
        String str = bMap.get(key);
        if (str == null) {
            bMap.put(key, value);
        }
        else {
            String newValue = str + ":" + value;
            bMap.put(key, newValue);
        }

       try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    /*
    sleep不会释放锁的
当两个map分别位于MyCounter和MyCounterV2中， MyRunnableA访问MyCounter的increase方法。 MyRunnableB也访问MyCounter中的increase方法
多个线程几乎可以同时调用increase方法，也就是试图访问两个map。 从数据看


BThreadId:13 :1525828550430
AThreadId:28 :1525828552430

AThreadId:12 :1525829567161  线程12访问了MyCounter的aMap， 时间1525829567161
BThreadId:31 :1525829569163  线程31访问了MyCounter的bMap， 时间1525829569163 两个相差2002毫秒， 而increase方法基本上需要2000毫秒执行时间
BThreadId:27 :1525829571163
AThreadId:28 :1525829573164
AThreadId:24 :1525829575164 线程12访问了MyCounter的aMap， 时间 1525829575164
BThreadId:23 :1525829577165 线程31访问了MyCounter的bMap， 时间 1525829577165 两个相差2001毫秒， 而increase方法基本上需要2000毫秒执行时间
AThreadId:30 :1525829579166
     */

}
